package user

import (
	"cat-collage-backend/internal/model"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"net/http"
)

func Regist(c *gin.Context, db *gorm.DB) {
	u, _ := c.GetPostForm("username")
	p, _ := c.GetPostForm("password")
	if u == "" || p == "" {
		c.JSON(400, gin.H{"error": "Please provide username and password"})
		return
	}
	user := &model.User{}
	if len(p) < 6 {
		c.JSON(400, gin.H{"error": "Password length must be greater than 6"})
		return
	}
	result := db.Where("username = ?", u).First(&user)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		user.Username = u
		user.Password = p
		uid, err := uuid.NewRandom()
		if err != nil {
			c.JSON(500, gin.H{"error": "Error"})
			return
		}
		user.ID = uid.String()
		db.Create(&user)
		c.JSON(200, gin.H{"msg": "success", "code": http.StatusOK})
		return
	} else {
		c.JSON(400, gin.H{"error": "User already exists"})
		return
	}
}
